package gateway

import (
	"context"
	"net/http"
	"strings"
	"sync"
	"time"
)

// AIPGatewayProxy  API网关代理
type AIPGatewayProxy struct {
	services   map[string]Service
	cache      *ResponseCache
	middleware []Middleware
	mu         sync.RWMutex
}

// NewAPIGatewayProxy 创建一个新的API网关代理
func NewAPIGatewayProxy() *AIPGatewayProxy {
	return &AIPGatewayProxy{
		services:   make(map[string]Service),
		cache:      NewResponseCache(),
		middleware: make([]Middleware, 0),
	}
}

// RegisterService 注册服务
func (p *AIPGatewayProxy) RegisterService(pathPrefix string, service Service) {
	p.mu.Lock()
	defer p.mu.Unlock()
	// 应用中间件
	for _, mw := range p.middleware {
		service = mw(service)
	}
	p.services[pathPrefix] = service
}

// Use 添加中间件
func (p *AIPGatewayProxy) Use(mw ...Middleware) {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.middleware = append(p.middleware, mw...)

	// 重新应用中间件到所有已注册的服务
	for pathPrefix, service := range p.services {
		for _, mw := range p.middleware {
			service = mw(service)
		}
		p.services[pathPrefix] = service
	}
}

// ServeHTTP 实现http.Handler接口，处理API请求
func (p *AIPGatewayProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 查找与请求路径匹配的服务
	service, ok := p.findServiceForRequest(r)
	if !ok {
		http.Error(w, "Service not found", http.StatusNotFound)
		return
	}

	// 检查缓存
	cacheKey := r.Method + ":" + r.URL.Path
	if resp, ok := p.cache.Get(cacheKey); ok {
		// 从缓存中返回响应
		resp.Write(w)
		return
	}

	// 转发请求
	ctx := context.Background()
	resp, err := service.HandleRequest(&ctx, r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// 缓存响应 仅限GET请求
	if r.Method == http.MethodGet {
		p.cache.Set(cacheKey, resp, 30 * time.Second)
	}

	// 写入响应
	resp.Write(w)
}

// findServiceForRequest 查找与请求路径匹配的服务
func (p *AIPGatewayProxy) findServiceForRequest(req *http.Request) (Service, bool) {
	p.mu.RLock()
	defer p.mu.RUnlock()

	for pathPrefix, service := range p.services {
		if strings.HasPrefix(req.URL.Path, pathPrefix) {
			return service, true
		}
	}
	return nil, false
}
